<template>
  <div class="app-container">
    <div v-show="!modifyInfo.visible && !detailInfo.visible">
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <NewPageFilter
          ref="pageFilter"
          v-model:query="filterInfo.query.queryMap"
          :query-more-json="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clear-type="clearType"
          :slip-select-request="slipSelectRequest"
        >
          <template v-slot:filter-isSatisfaction="scope">
            <SelectModel
              v-model.lazy="filterInfo.query.queryParams.isSatisfaction"
              type-code="satisfactory_evaluation"
              :clearable="true"
              :checkDefault="false"
              placeholder="请选择是否满意"
              @change="search"
            />
          </template>
        </NewPageFilter>
      </div>

      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btList"> </NewPageFilter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :tab-index="false"
        :check-box="true"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        @pageInfo="pageInfo"
        :row-class-name="tableRowClassName"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-orderNo="scope">
          <p class="slip-edit" @click="showProductDetail(scope.row)">
            {{ scope.row.orderNo || '-' }}
          </p>
        </template>
      </table-container>
    </div>
    <!-- 新增或修改 -->
    <RepairOrderModify
      v-if="modifyInfo.visible"
      :id="modifyInfo.id"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      @returnModify="returnModify"
    />

    <!-- 详情页 -->
    <repairOrder-detail
      v-if="detailInfo.visible"
      :id="detailInfo.id"
      v-model:visible="detailInfo.visible"
      :title="detailInfo.title"
      :noOrderType="true"
      @returnBack="getList"
      @returnUpdate="returnUpdate"
    />

    <set-preference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :search-list="filterInfo.searchList"
      :field-list="tableInfo.fieldList"
      :customize-user-v-o="filterInfo.query.customizeUserVO"
      @callback="setPreferenceCallback"
    />
    <advanced-search
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      :field-list="tableInfo.fieldList"
      v-model:form-data="advancedSearchInfo.data"
      @callback="advancedSearchCallback"
    />

    <!-- 派单/改派 -->
    <page-dialog
      v-show="sendOrderInfo.visible"
      :title="sendOrderInfo.title"
      v-model:visible="sendOrderInfo.visible"
      :width="sendOrderInfo.width"
      :bt-loading="sendOrderInfo.btLoading"
      :bt-list="sendOrderInfo.btList"
    >
      <page-form
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="sendOrderInfo.formInfo.ref"
        :data="sendOrderInfo.formInfo.data"
        :field-list="sendOrderInfo.formInfo.fieldList"
        :rules="sendOrderInfo.formInfo.rules"
        :label-width="sendOrderInfo.formInfo.labelWidth"
      >
        <template v-slot:form-requireCompleteTime>
          <el-date-picker
            v-model="sendOrderInfo.formInfo.data.requireCompleteTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择日期"
          >
          </el-date-picker>
        </template>
        <template v-slot:form-acceptUserName>
          <el-input
            type="input"
            :disabled="true"
            class="not-mongolia"
            placeholder="请选择维修人员"
            v-model="sendOrderInfo.formInfo.data.acceptUserName"
          >
            <template #append>
              <el-icon @click="openRepairUserWindow"><MoreFilled /></el-icon>
            </template>
          </el-input>
        </template>
      </page-form>
    </page-dialog>
    <!-- 维修人员 -->
    <SelectRepairUser
      v-if="selectRepairUserInfo.visible"
      v-model:showDialog="selectRepairUserInfo.visible"
      :check-box="true"
      :checkedRowList="selectRepairUserInfo.checkedRowList"
      :saveEmpty="true"
      :highlight-row="true"
      :api="selectRepairUserInfo.api"
      :query="selectRepairUserInfo.query"
      @callback="selectRepairUserCallBack"
    />
    <!-- 处理登记 -->
    <page-dialog
      v-show="registerInfo.visible"
      :title="registerInfo.title"
      v-model:visible="registerInfo.visible"
      :width="registerInfo.width"
      :bt-loading="registerInfo.btLoading"
      :bt-list="registerInfo.btList"
    >
      <page-form
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="registerInfo.formInfo.ref"
        :data="registerInfo.formInfo.data"
        :field-list="registerInfo.formInfo.fieldList"
        :rules="registerInfo.formInfo.rules"
        :label-width="registerInfo.formInfo.labelWidth"
      >
        <template v-slot:form-startTime>
          <el-date-picker
            v-model="registerInfo.formInfo.data.startTime"
            type="datetime"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm"
            placeholder="请选择开始时间"
          >
          </el-date-picker>
        </template>
        <template v-slot:form-endTime>
          <el-date-picker
            v-model="registerInfo.formInfo.data.endTime"
            type="datetime"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm"
            placeholder="请选择结束时间"
          >
          </el-date-picker>
        </template>
        <template v-slot:form-filePathList>
          <el-upload
            :headers="registerInfo.uploadInfo.headers"
            :on-error="uploadError"
            :on-success="uploadAttachment"
            :on-remove="uploadRemove"
            :before-upload="beforeProductUpload"
            :on-exceed="handleExceed"
            :action="registerInfo.uploadInfo.action"
            :limit="registerInfo.uploadInfo.limit"
            :file-list="registerInfo.uploadInfo.fileList"
          >
            <el-button>点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              文件大小不超过{{
                $store.state.permission.systemConfig.max_file_size
              }}M
            </div>
          </el-upload>
        </template>
      </page-form>
    </page-dialog>
    <!-- 完工 -->
    <page-dialog
      v-show="finishInfo.visible"
      :title="finishInfo.title"
      v-model:visible="finishInfo.visible"
      :width="finishInfo.width"
      :bt-loading="finishInfo.btLoading"
      :bt-list="finishInfo.btList"
    >
      <page-form
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="finishInfo.formInfo.ref"
        :data="finishInfo.formInfo.data"
        :field-list="finishInfo.formInfo.fieldList"
        :rules="finishInfo.formInfo.rules"
        :label-width="finishInfo.formInfo.labelWidth"
      >
        <template v-slot:form-completeTime>
          <el-date-picker
            v-model="finishInfo.formInfo.data.completeTime"
            type="datetime"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm"
            placeholder="选择完工时间"
          >
          </el-date-picker>
        </template>
      </page-form>
    </page-dialog>
    <!-- 评价 -->
    <page-dialog
      v-show="estimateInfo.visible"
      :title="estimateInfo.title"
      v-model:visible="estimateInfo.visible"
      :width="estimateInfo.width"
      :bt-loading="estimateInfo.btLoading"
      :bt-list="estimateInfo.btList"
    >
      <Rate
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="estimateInfo.formInfo.ref"
        :data="estimateInfo.formInfo.data"
        :field-list="estimateInfo.formInfo.fieldList"
        :rules="estimateInfo.formInfo.rules"
        :label-width="estimateInfo.formInfo.labelWidth"
      >
      </Rate>
    </page-dialog>
    <!-- 院外报修 -->
    <page-dialog
      v-show="outsideRepairInfo.visible"
      :title="outsideRepairInfo.title"
      v-model:visible="outsideRepairInfo.visible"
      :width="outsideRepairInfo.width"
      :bt-loading="outsideRepairInfo.btLoading"
      :bt-list="outsideRepairInfo.btList"
    >
      <page-form
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="outsideRepairInfo.formInfo.ref"
        :data="outsideRepairInfo.formInfo.data"
        :field-list="outsideRepairInfo.formInfo.fieldList"
        :rules="outsideRepairInfo.formInfo.rules"
        :label-width="outsideRepairInfo.formInfo.labelWidth"
      >
        <template v-slot:form-requireCompleteTime>
          <el-date-picker
            v-model="outsideRepairInfo.formInfo.data.requireCompleteTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择日期"
          >
          </el-date-picker>
        </template>
        <template v-slot:form-maintenanceName>
          <el-input
            type="input"
            :disabled="true"
            :class="disabledMaintenanceName ? '' : 'not-mongolia'"
            placeholder="请选择维保商"
            v-model="outsideRepairInfo.formInfo.data.maintenanceName"
          >
            <template #append>
              <el-icon @click="openMaintenanceProviderWindow"
                ><MoreFilled
              /></el-icon>
            </template>
          </el-input>
        </template>
        <template v-slot:form-maintenanceUserName>
          <el-input
            v-model="outsideRepairInfo.formInfo.data.maintenanceUserName"
            type="input"
            :disabled="true"
            class="not-mongolia"
            placeholder="请选择维保联系人"
          >
            <template #append>
              <el-icon @click="openMaintenanceContactsList"
                ><MoreFilled
              /></el-icon>
            </template>
          </el-input>
        </template>
      </page-form>
    </page-dialog>
    <!-- 维保商 -->
    <select-maintenance
      v-if="selectMaintenanceProvider.visible"
      v-model:show-dialog="selectMaintenanceProvider.visible"
      :query="selectMaintenanceProvider.query"
      :check-box="false"
      :saveEmpty="true"
      :highlight-row="true"
      @callback="selectMaintenanceProviderCallback"
    />
    <!-- 维保联系人 -->
    <SelectRepairUser
      v-if="selectMaintenanceContactsInfo.visible"
      v-model:showDialog="selectMaintenanceContactsInfo.visible"
      :api="selectMaintenanceContactsInfo.api"
      :saveEmpty="true"
      :query="selectMaintenanceContactsInfo.query"
      :check-box="false"
      :highlight-row="true"
      :showPermission="false"
      @callback="selectMaintenanceContactsCallBack"
    />
    <page-dialog
      v-show="dialogInfo.visible"
      :title="dialogInfo.title"
      v-model:visible="dialogInfo.visible"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <div class="asset-msg">
        <div class="asset-msg-label">
          <i class="el-icon-warning"></i>{{ dialogInfo.msg }}：
        </div>
        <el-radio-group v-model="dialogInfo.flag">
          <el-radio :label="true">当前页数据</el-radio>
          <el-radio :label="false">全部页数据</el-radio>
        </el-radio-group>
      </div>
    </page-dialog>
  </div>
</template>

<script setup name="repairOrder">
import {
  getDispatchUserAll,
  reminderRepairOrder,
  repairDealAffair,
  confirmRepairOrder,
  cannelRepairOrder,
  completeDealRepairOrder,
  deleteRepairOrder,
  dispatchRepairOrder,
  updateDispatchRepairOrder,
  revokeRepairOrder,
  getRepairOrderCustomizeListPage,
  submitRepairOrder,
  approvedRepairOrder,
  rejectRepairOrder,
  refuseRepairOrder,
  recallRepairOrder,
  cancelCheckRepairOrder,
  deleteSavedRepairOrder,
  downloadFileRepairOrder,
  getSelectUserWithPermission,
  transferRepairOrder,
  excelRepairOrder
} from '@/api/repair.js'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import { getBusinessKeyById } from '@/api/flowable'
import { ElLoading, ElMessage } from 'element-plus'
import axios from 'axios'
import RepairOrderModify from '@/views/repair/repairManage/repairOrder/modify.vue'
import RepairOrderDetail from '@/views/repair/repairManage/repairOrder/details.vue'
import SelectRepairUser from '@/components/SelectUsers/selectMaintenanceUsers'
import {
  getAssetById,
  getDepotsSelectAllAndMaintenanceGroup,
  getDeptsSelectAllAndMaintenanceGroup,
} from '@/api/core'
import moment from 'moment'

const { proxy } = getCurrentInstance()
const emit = defineEmits()
const router = useRouter()
const route = useRoute()

const props = defineProps(['query'])

let validateTime = (rule, value, callback) => {
  let currentTime = moment(new Date()).format('YYYY-MM-DD')
  let requireTime = moment(value).format('YYYY-MM-DD')
  if (requireTime < currentTime) {
    callback(new Error('要求完成时间不能小于当前日期！'))
  } else {
    callback()
  }
}
let validateCompleteTime = (rule, value, callback) => {
  let currentTime = moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
  if (value > currentTime) {
    callback(new Error('完工时间不能大于当前时间！'))
  } else {
    callback()
  }
}

let validateStartTime = (rule, value, callback) => {
  let endTime = registerInfo.formInfo.data.endTime
  if (endTime) {
    if (endTime < value) {
      callback(new Error('开始时间不能大于结束时间！'))
    } else {
      callback()
    }
  } else {
    callback()
  }
}
let validateEndTime = (rule, value, callback) => {
  let startTime = registerInfo.formInfo.data.startTime
  if (startTime) {
    if (startTime > value) {
      callback(new Error('结束时间不能小于开始时间！'))
    } else {
      callback()
    }
  } else {
    callback()
  }
}
const dialogInfo = ref({
  visible: false,
  title: '提示',
  btLoading: false,
  type: '',
  msg: '',
  width: '400px',
  flag: true,
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '打印',
      type: 'primary',
      event: checkConfirm,
      show: true,
    },
  ],
})
const productionTimePickerOptions = ref({})
const isDispatchUser = ref(false)
const clearType = ref(true)
const slipSelectRequest = ref(true)

const listTypeInfo = reactive({
  typeList: [],
})
const filterInfo = reactive({
  query: {
    sortString: '',
    customizeUserVO: {},
    queryMap: {
      assetSourceAuth: {
        asTbName: 'repair_order,repair_order',
        columnName: 'use_dept_id,depot_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'assetSourceAuth',
      },
    },
    queryParams: {
      isSatisfaction: '',
    },
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btList: [
    {
      type: 'button',
      label: '新增',
      event: create,
      show: proxy.$permission('repairOrder:add'),
    },

    {
      type: 'slot',
      value: 'reminder',
      show: proxy.$permission('repairOrder:reminder'),
    },
    {
      type: 'button',
      label: '下载附件',
      event: downloadFile,
      show: proxy.$permission('repairOrder:downloadFile'),
    },
    {
      event: exportExcel,
      label: '导出excel',
      type: 'button',
      show: proxy.$permission('repairOrder:exportExcel'),
    },
  ],
})

const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '120',
    btList: [
      {
        label: '删除',
        event: remove,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: proxy.$permission('repairOrder:delete'),
        ifRender: removeIfRender,
      },
      {
        label: '催单',
        event: reminder,
        show: proxy.$permission('repairOrder:reminder'),
        ifRender: function (row) {
          return (
            row.maintainChannel !== 1 &&
            (row.status === 1 || row.status === 2 || row.status === 3)
          )
        },
      },
      {
        label: '撤销',
        popconfirmText: '撤销后将改变数据,是否继续？',
        event: revoke,
        show: proxy.$permission('repairOrder:revoke'),
        ifRender: revokeIfRender,
      },
      {
        label: '派单',
        event: sendOrder,
        show: proxy.$permission('repairOrder:sendOrder'),
        ifRender: sendOrderIfRender,
      },
      {
        label: '改派',
        event: updateSendOrder,
        show: proxy.$permission('repairOrder:updateSendOrder'),
        ifRender: updateSendOrderIfRender,
      },
      {
        label: '处理登记',
        event: handleRegister,
        show: proxy.$permission('repairOrder:handleRegister'),
        ifRender: handleRegisterIfRender,
      },
      {
        label: '完工',
        event: finish,
        show: proxy.$permission('repairOrder:finish'),
        ifRender: finishIfRender,
      },
      {
        label: '院外报修',
        event: transfer,
        show: proxy.$permission('repairOrder:transfer'),
        ifRender: transferIfRender,
      },

      {
        label: '评价',
        event: estimate,
        show: proxy.$permission('repairOrder:estimate'),
        ifRender: estimateIfRender,
      },
      {
        label: '取消完工',
        popconfirmText: '取消完工后将改变数据,是否继续？',
        event: cancelFinish,
        show: proxy.$permission('repairOrder:cancelFinish'),
        ifRender: cancelFinishIfRender,
      },
      {
        label: '修改',
        event: update,
        show: proxy.$permission('repairOrder:update'),
        ifRender: updateIfRender,
      },
      {
        label: '提交',
        event: submit,
        show: proxy.$permission('repairOrder:submit'),
        ifRender: updateIfRender,
      },
      {
        label: '批准',
        event: (row) => btnFlow(row, 'approve'),
        show: proxy.$permission('repairOrder:approve'),
        ifRender: checkIfRenderBtnFlow,
      },
      {
        label: '驳回',
        event: (row) => btnFlow(row, 'reject'),
        show: proxy.$permission('repairOrder:reject'),
        ifRender: checkIfRenderBtnFlow,
      },
      {
        label: '拒绝',
        event: (row) => btnFlow(row, 'refuse'),
        show: proxy.$permission('repairOrder:refuse'),
        ifRender: checkIfRenderBtnFlow,
      },
      {
        label: '销审',
        event: salesReview,
        show: proxy.$permission('repairOrder:salesReview'),
        ifRender: checkIfRenderSalesReview,
      },
      {
        label: '撤回',
        event: recall,
        show: proxy.$permission('repairOrder:recall'),
        ifRender: checkIfRenderRecall,
      },
      {
        label: '删除',
        event: _delete,
        show: proxy.$permission('repairOrder:delete'),
        ifRender: updateIfRender,
      },
    ],
  },
})
const printerInfo = reactive({
  visible: false,
  data: {},
})
const detailListInfo = reactive({
  visible: false,
})
//明细相关
const detailInfo = reactive({
  visible: false,
  title: '报修单详情',
  id: '',
})
//新增或更新相关
const modifyInfo = reactive({
  visible: false,
  title: '',
  id: '',
})

const preferenceInfo = reactive({
  visible: false,
})
const advancedSearchInfo = reactive({
  visible: false,
  data: {},
})

//派单、改派相关
const sendOrderInfo = reactive({
  visible: false,
  title: '',
  btLoading: false,
  type: '',
  msg: '',
  width: '40%',
  flag: true,
  btList: [
    { label: '关闭', event: handleCloseSendOrder, show: true },
    {
      label: '保存',
      type: 'primary',
      event: saveSendOrder,
      show: true,
    },
  ],

  formInfo: {
    ref: null,
    data: {},
    fieldList: [
      {
        label: '要求完成时间',
        value: 'requireCompleteTime',
        type: 'slot',
        // required: true,
      },
      {
        label: '派单给',
        value: 'acceptUserName',
        type: 'slot',
        required: true,
      },
      {
        label: '派单说明',
        value: 'dispatchDescribe',
        type: 'textarea',
      },
    ],
    rules: {
      requireCompleteTime: [
        // {
        //   required: true,
        //   message: '请选择要求完成时间',
        //   trigger: 'change',
        // },
        {
          validator: validateTime,
          trigger: 'blur',
        },
      ],
      acceptUserName: [
        {
          required: true,
          message: '请选择维修人员',
          trigger: 'change',
        },
      ],
    },
    labelWidth: '120px',
  },
})
//处理登记相关
const registerInfo = reactive({
  visible: false,
  title: '处理登记',
  btLoading: false,
  type: '',
  msg: '',
  width: '40%',
  flag: true,
  btList: [
    { label: '关闭', event: handleCloseRegister, show: true },
    {
      label: '保存',
      type: 'primary',
      event: saveRegister,
      show: true,
    },
  ],

  formInfo: {
    ref: null,
    data: {},
    fieldList: [
      {
        label: '处理人',
        value: 'dealUserName',
        type: 'input',
        disabled: true,
      },

      {
        label: '开始时间',
        value: 'startTime',
        type: 'slot',
        required: true,
      },
      {
        label: '结束时间',
        value: 'endTime',
        type: 'slot',
        required: true,
      },
      {
        label: '处理进度(%)',
        value: 'dealRate',
        type: 'number',
        precision: 2,
        max: 100,
        // required: true,
      },
      {
        label: '工作说明',
        value: 'dealDescribe',
        type: 'textarea',
        required: true,
      },
      {
        label: '附件',
        value: 'filePathList',
        type: 'slot',
        className: 'not-br',
      },
    ],
    rules: {
      startTime: [
        {
          required: true,
          message: '请选择开始时间',
          trigger: 'change',
        },
        {
          validator: validateStartTime,
          trigger: 'blur',
        },
      ],
      endTime: [
        {
          required: true,
          message: '请选择结束时间',
          trigger: 'change',
        },
        {
          validator: validateEndTime,
          trigger: 'blur',
        },
      ],
      dealDescribe: [
        {
          required: true,
          message: '请输入工作说明',
          trigger: 'blur',
        },
      ],
    },
    labelWidth: '110px',
  },
  uploadInfo: {
    action: axios.defaults.baseURL + '/pub/uploadfile',
    headers: {
      Authorization: proxy.$store.state.user.token,
    },
    loading: {},
    limit: 3,
    fileList: [],
    fileSize: proxy.$store.state.permission.systemConfig.max_file_size,
    fileType: [
      'png',
      'jpg',
      'jpeg',
      'pdf',
      'mp3',
      'm4a',
      'aac',
      'wav',
      'audio',
      'x-m4a',
      'doc',
      'docx',
      'xls',
      'xlsx',
    ],
  },
})
//完工相关
const finishInfo = reactive({
  visible: false,
  title: '完工',
  btLoading: false,
  type: '',
  msg: '',
  width: '40%',
  flag: true,
  btList: [
    { label: '关闭', event: handleCloseFinish, show: true },
    {
      label: '保存',
      type: 'primary',
      event: saveFinish,
      show: true,
    },
  ],

  formInfo: {
    ref: null,
    data: {},
    fieldList: [
      {
        label: '完工时间',
        value: 'completeTime',
        type: 'slot',
        required: true,
      },
      {
        label: '完工说明',
        value: 'completeDescribe',
        type: 'textarea',
        required: true,
      },
    ],
    rules: {
      completeTime: [
        {
          required: true,
          message: '请选择完工时间',
          trigger: 'change',
        },
        {
          validator: validateCompleteTime,
          trigger: 'blur',
        },
      ],
      completeDescribe: [
        {
          required: true,
          message: '请输入完工说明',
          trigger: 'blur',
        },
      ],
    },
    labelWidth: '100px',
  },
})
//院外报修
const outsideRepairInfo = reactive({
  visible: false,
  title: '院外报修',
  btLoading: false,
  type: '',
  msg: '',
  width: '40%',
  flag: true,
  btList: [
    { label: '关闭', event: handleCloseOutsideRepair, show: true },
    {
      label: '保存',
      type: 'primary',
      event: saveOutsideRepair,
      show: true,
    },
  ],

  formInfo: {
    ref: null,
    data: {},
    fieldList: [
      {
        label: '资产',
        value: 'assetName',
        type: 'input',
        required: true,
        disabled: false,
      },
      {
        label: '要求完成时间',
        value: 'requireCompleteTime',
        type: 'slot',
        // required: true,
      },
      {
        label: '维保商',
        value: 'maintenanceName',
        type: 'slot',
        required: true,
      },
      {
        label: '维保商联系人',
        value: 'maintenanceUserName',
        type: 'slot',
      },
      {
        label: '维保商联系人电话',
        value: 'maintenanceUserTel',
        type: 'input',
      },
    ],
    rules: {
      assetName: [
        {
          required: true,
          message: '请输入资产',
          trigger: 'blur',
        },
      ],
      requireCompleteTime: [
        // {
        //   required: true,
        //   message: '请选择要求完成时间',
        //   trigger: 'change',
        // },
        {
          validator: validateTime,
          trigger: 'blur',
        },
      ],
      maintenanceName: [
        {
          required: true,
          message: '请选择维保商',
          trigger: 'change',
        },
      ],
      maintenanceUserTel: [
        {
          validator: proxy.$validate.cellphone,
          trigger: 'blur',
        },
      ],
    },
    labelWidth: '150px',
  },
})
//评价相关
const estimateInfo = reactive({
  visible: false,
  title: '评价',
  btLoading: false,
  type: '',
  msg: '',
  width: '30%',
  flag: true,
  btList: [
    { label: '关闭', event: handleCloseEstimate, show: true },
    {
      label: '保存',
      type: 'primary',
      event: saveEstimate,
      show: true,
      disabled: true,
    },
  ],

  formInfo: {
    ref: null,
    data: {},
    fieldList: [
      {
        label: '是否已修复',
        value: 'isRepair',
        type: 'radio-model',
        code: 'yes_or_no',
        className: 'isReprir',
      },
      {
        label: '综合评分',
        value: 'compositeScore',
        type: 'showText',
        texts: ['1.0', '2.0', '3.0', '4.0', '5.0'],
      },
      {
        label: '服务态度',
        value: 'serviceAttitude',
        type: 'showText',
        texts: ['1.0', '2.0', '3.0', '4.0', '5.0'],
      },
      {
        label: '响应速度',
        value: 'responseSpeed',
        type: 'showText',
        texts: ['1.0', '2.0', '3.0', '4.0', '5.0'],
      },
      {
        label: '技术水平',
        value: 'skillLevel',
        type: 'showText',
        texts: ['1.0', '2.0', '3.0', '4.0', '5.0'],
      },
      {
        label: '建议评价',
        value: 'suggest',
        type: 'textarea',
        placeholder: '为了更好的为您服务，请留下您宝贵的意见',
      },
    ],
    rules: {},
    labelWidth: '120px',
  },
})
let page = reactive({
  page: true,
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})
//选择维修人员
const selectRepairUserInfo = reactive({
  visible: false,
  saveEmpty: true,
  api: getSelectUserWithPermission,
  query: {
    orgId: '',
    assetId: '',
    deptId: '',
    depotId: '',
    assetClassifyId: '',
    notAssetRepairType: '',
  },
  checkedRowList: [],
})
const selectMaintenanceContactsInfo = reactive({
  visible: false,
  saveEmpty: true,
  api: getSelectUserWithPermission,
  query: {
    orgId: '',
    assetId: '',
    deptId: '',
    depotId: '',
    assetClassifyId: '',
    notAssetRepairType: '',
  },
})
const selectMaintenanceProvider = reactive({
  visible: false,
  query: {
    orgId: '',
  },
})
const disabledMaintenanceName = ref(false)
const canReminder = computed(() => {
  return (
    tableInfo.selections.length &&
    !tableInfo.selections.filter(
      (item) =>
        item.maintainChannel === 1 ||
        (item.status !== 1 && item.status !== 2 && item.status !== 3)
    ).length
  )
})
const toPage = computed(() => {
  return proxy.$store.state.settings.toPage
})

let stopWatch = function () {}
onActivated(() => {
  stopWatch = watch(
    () => toPage.value,
    (val) => {
      console.log(val, 'toPage.value')
      if (val) {
        let menus = proxy.$store.state.permission.defaultMenus
        menus.forEach((item) => {
          if (item.children) {
            item.children.forEach((el) => {
              if (el.code === 'repairOrder' && el.url === val.url) {
                detailInfo.visible = false
                sendOrderInfo.visible = false
                registerInfo.visible = false
                finishInfo.visible = false
                modifyInfo.visible = false
                estimateInfo.visible = false
                advancedSearchInfo.visible = false
                preferenceInfo.visible = false
                selectRepairUserInfo.visible = false
                if (val.urlType === 1) {
                  getList()
                } else if (val.urlType === 2) {
                  detailInfo.visible = true
                  detailInfo.id = val.businessId
                  sessionStorage.setItem('storeRowId', val.businessId)
                }
                proxy.$store.dispatch('settings/toPage', '')
              }
            })
          }
        })
      }
    },
    {
      deep: true,
      immediate: true,
    }
  )
})
onDeactivated(() => {
  stopWatch()
})
watch(
  () => estimateInfo.formInfo.data,
  (val) => {
    if (val) {
      if (
        (val.isRepair == 1 || val.isRepair == 0) &&
        val.compositeScore &&
        val.serviceAttitude &&
        val.responseSpeed &&
        val.skillLevel
      ) {
        estimateInfo.btList[1].disabled = false
      } else {
        estimateInfo.btList[1].disabled = true
      }
    } else {
      estimateInfo.btList[1].disabled = true
    }
  },
  {
    deep: true,
  }
)
watch(
  () => proxy.$router.currentRoute.value.name,
  (to, from) => {
    if (!from) return
    if (
      from.includes('myPendingDetail') ||
      from.includes('myFinishedDetail') ||
      from.includes('myApplyDetail')
    ) {
      getList()
    }
  },
  {
    deep: true,
  }
)

let obj = {
  assetName: {
    label: '资产名称',
    value: 'assetName',
    componentType: 'input',
    show: false,
    type: 'column',
    hidden: true,
  },
  statusValue: {
    label: '状态',
    value: 'statusValue',
    asValue: 'status',
    componentType: 'select-model',
    code: 'repair_order_status',
    show: false,
    hidden: true,
  },
  repairTypeName: {
    label: '报修类型',
    value: 'repairTypeName',
    asValue: 'repairType',
    componentType: 'select-model',
    code: 'repair_type_enum',
    show: false,
    hidden: true,
  },
  depotName: {
    label: '出库仓库',
    value: 'depotName',
    asValue: 'depotId',
    componentType: 'slip-select',
    query: {
      depotAuth: 'id',
      status: 1,
      useTypeId: '2',
    },
    api: getDepotsSelectAllAndMaintenanceGroup,
    show: false,
    hidden: true,
  },
  useDeptName: {
    label: '使用部门',
    value: 'useDeptName',
    asValue: 'useDeptId',
    query: {
      deptAuth: 'id',
      status: 1,
    },
    api: getDeptsSelectAllAndMaintenanceGroup,
    componentType: 'slip-select',
    show: false,
    hidden: true,
  },
  appraisalContent: {
    label: '鉴定内容',
    value: 'appraisalContent',
    componentType: 'input',
    show: false,
    type: 'column',
    hidden: true,
  },
}
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
filterInfo.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
getCustomize()

onMounted(() => {
  getDispatchUser()
})
//导出excel
async function exportExcel() {
  dialogInfo.value.flag = true
  dialogInfo.value.visible = true
  dialogInfo.value.type = 'excel'
  dialogInfo.value.msg = '请选择数据导出范围'
  dialogInfo.value.btList[1].label = '导出'
}
function exportExcelList() {
  let query = {
    customizeDto: filterInfo.query,
  }
  let params = {
    ...query,
    ...page,
    page: dialogInfo.value.flag,
  }
  excelRepairOrder(params).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
function handleClose() {
  dialogInfo.value.visible = false
}
function checkConfirm() {
  if (dialogInfo.value.type === 'excel') {
    exportExcelList()
  }
  dialogInfo.value.visible = false
  dialogInfo.value.msg = ''
}
//维保商
function openMaintenanceProviderWindow() {
  if (!disabledMaintenanceName.value) {
    selectMaintenanceProvider.visible = true
  }
}
//维保联系人
function openMaintenanceContactsList() {
  if (outsideRepairInfo.formInfo.data.maintainChannel == 1) {
    if (!outsideRepairInfo.formInfo.data.maintenanceName) {
      proxy.$message({
        type: 'warning',
        duration: 3500,
        message: '请先选择维保商',
        showClose: true,
      })
      return
    }
  }
  selectMaintenanceContactsInfo.query.orgId =
    outsideRepairInfo.formInfo.data.maintenanceId === -2
      ? ''
      : outsideRepairInfo.formInfo.data.maintenanceId

  selectMaintenanceContactsInfo.query.assetId =
    outsideRepairInfo.formInfo.data.assetId === -2
      ? ''
      : outsideRepairInfo.formInfo.data.assetId

  selectMaintenanceContactsInfo.query.deptId =
    outsideRepairInfo.formInfo.data.useDeptId === -2
      ? ''
      : outsideRepairInfo.formInfo.data.useDeptId

  selectMaintenanceContactsInfo.query.depotId =
    outsideRepairInfo.formInfo.data.depotId === -2
      ? ''
      : outsideRepairInfo.formInfo.data.depotId

  selectMaintenanceContactsInfo.query.assetClassifyId =
    outsideRepairInfo.formInfo.data.classifyType === -2
      ? ''
      : outsideRepairInfo.formInfo.data.classifyType
  selectMaintenanceContactsInfo.query.notAssetRepairType =
    outsideRepairInfo.formInfo.data.notAssetRepairType === -2
      ? ''
      : outsideRepairInfo.formInfo.data.notAssetRepairType

  selectMaintenanceContactsInfo.visible = true
}
//维保商
function selectMaintenanceProviderCallback(row) {
  if (row) {
    outsideRepairInfo.formInfo.data.maintenanceName = row.maintenanceName
    outsideRepairInfo.formInfo.data.maintenanceId = row.maintenanceId
    outsideRepairInfo.formInfo.data.maintenanceUser = ''
    outsideRepairInfo.formInfo.data.maintenanceUserName = ''
  } else {
    outsideRepairInfo.formInfo.data.maintenanceName = ''
    outsideRepairInfo.formInfo.data.maintenanceId = ''
    outsideRepairInfo.formInfo.data.maintenanceUser = ''
    outsideRepairInfo.formInfo.data.maintenanceUserName = ''
  }
}
//维保联系人
function selectMaintenanceContactsCallBack(row) {
  if (row) {
    outsideRepairInfo.formInfo.data.maintenanceUser = row.userId
    outsideRepairInfo.formInfo.data.maintenanceUserName = row.name
    outsideRepairInfo.formInfo.data.maintenanceUserTel = row.tel
  } else {
    outsideRepairInfo.formInfo.data.maintenanceUser = -2
    outsideRepairInfo.formInfo.data.maintenanceUserName = ''
    outsideRepairInfo.formInfo.data.maintenanceUserTel = ''
  }
}
function handleCloseOutsideRepair() {
  outsideRepairInfo.visible = false
  outsideRepairInfo.formInfo.data = {}
}
function saveOutsideRepair() {
  outsideRepairInfo.formInfo.ref.validate((valid) => {
    if (valid) {
      transferRepairOrder(outsideRepairInfo.formInfo.data).then((resp) => {
        if (resp && resp.success) {
          getList()
        }
        outsideRepairInfo.formInfo.data = {}
        outsideRepairInfo.visible = false
      })
    }
  })
}
function transfer(row) {
  //院外报修

  if (row.assetId > 0) {
    outsideRepairInfo.formInfo.fieldList.forEach((item) => {
      if (item.value === 'assetName') {
        item.disabled = true
      }
    })
  } else {
    outsideRepairInfo.formInfo.fieldList.forEach((item) => {
      if (item.value === 'assetName') {
        item.disabled = false
      }
    })
  }
  selectMaintenanceProvider.query.orgId = row.orgId

  outsideRepairInfo.formInfo.data.assetId = row.assetId
  outsideRepairInfo.formInfo.data.orderId = row.id
  outsideRepairInfo.formInfo.data.classifyType = row.classifyType
  outsideRepairInfo.formInfo.data.notAssetRepairType = row.notAssetRepairType
  outsideRepairInfo.formInfo.data.useDeptId = row.useDeptId
  outsideRepairInfo.formInfo.data.depotId = row.depotId

  outsideRepairInfo.formInfo.data.maintainChannel = row.maintainChannel

  outsideRepairInfo.formInfo.data.assetName = row.assetName
  outsideRepairInfo.formInfo.data.requireCompleteTime = row.expectCompleteTime

  if (row.assetId && row.assetId !== -2) {
    getAssetById(row.assetId).then((res) => {
      if (res && res.success) {
        if (res.data.maintenanceProviderName) {
          disabledMaintenanceName.value = true
        }
        outsideRepairInfo.formInfo.data.maintenanceName =
          res.data.maintenanceProviderName || ''
        outsideRepairInfo.formInfo.data.maintenanceId =
          res.data.maintenanceProvider === -2
            ? ''
            : res.data.maintenanceProvider

        proxy.$nextTick(() => {
          if (outsideRepairInfo.formInfo.ref) {
            outsideRepairInfo.formInfo.ref.clearValidate()
          }
        })
      }
    })
  } else {
    if (row.maintenanceName) {
      disabledMaintenanceName.value = true
    }
    outsideRepairInfo.formInfo.data.maintenanceName = row.maintenanceName || ''
    outsideRepairInfo.formInfo.data.maintenanceId =
      row.maintenanceId === -2 ? '' : row.maintenanceId
  }

  outsideRepairInfo.visible = true
  proxy.$nextTick(() => {
    if (outsideRepairInfo.formInfo.ref) {
      outsideRepairInfo.formInfo.ref.clearValidate()
    }
  })
}
function downloadFile() {
  downloadFileRepairOrder(filterInfo.query).then((res) => {
    if (res) {
      proxy.$fn.parseExcel(res)
    }
  })
}
function getDispatchUser() {
  getDispatchUserAll().then((res) => {
    if (res && res.success) {
      res.data.forEach((item) => {
        if (item.userId === proxy.$store.state.user.userInfo.user.id) {
          isDispatchUser.value = true
        }
      })
    }
  })
}
function sendOrderIfRender(row) {
  return (
    row.maintainChannel !== 1 &&
    row.status === 1 &&
    (isDispatchUser.value ||
      proxy.$store.state.user.userInfo.user.type !== 'normal')
  )
}
function updateSendOrderIfRender(row) {
  return (
    row.maintainChannel !== 1 &&
    (row.status === 2 || row.status === 5) &&
    (isDispatchUser.value ||
      proxy.$store.state.user.userInfo.user.type !== 'normal')
  )
}
function handleRegisterIfRender(row) {
  return (
    row.maintainChannel !== 1 &&
    (row.status === 1 || row.status === 2) &&
    (isDispatchUser.value ||
      proxy.$store.state.user.userInfo.user.type !== 'normal')
  )
}
// 撤销
function revokeIfRender(row) {
  return (
    (row.status === 1 || row.status === 2) &&
    (row.repairUser === proxy.$store.state.user.userInfo.user.id ||
      proxy.$store.state.user.userInfo.user.type !== 'normal')
  )
}
function finishIfRender(row) {
  return (
    row.maintainChannel !== 1 &&
    (row.status === 1 || row.status === 2) &&
    (isDispatchUser.value ||
      proxy.$store.state.user.userInfo.user.type !== 'normal')
  )
}
function transferIfRender(row) {
  return (
    row.maintainChannel !== 1 &&
    (row.status === 1 || row.status === 2 || row.status === 5) &&
    (isDispatchUser.value ||
      proxy.$store.state.user.userInfo.user.type !== 'normal')
  )
}
function estimateIfRender(row) {
  // 系统配置为是  且 当前等于报修人  则显示
  // 系统配置为否
  return (
    // proxy.$store.state.permission.systemConfig.repair_evaluation_only_oneself
    row.status === 4 &&
    (proxy.$store.state.user.userInfo.user.type !== 'normal' ||
      proxy.$store.state.permission.systemConfig
        .repair_evaluation_only_oneself == 0 ||
      (proxy.$store.state.permission.systemConfig
        .repair_evaluation_only_oneself == 1 &&
        row.repairUser === proxy.$store.state.user.userInfo.user.id))
  )
}
function updateIfRender(row) {
  return (
    (row.status === 8 || row.status === 12) &&
    (row.repairUser === proxy.$store.state.user.userInfo.user.id ||
      proxy.$store.state.user.userInfo.user.type !== 'normal')
  )
}
// 批准/驳回/拒绝
function checkIfRenderBtnFlow(row) {
  return (
    proxy.$store.state.permission.systemConfig.allow_repair_approval == 1 &&
    row.status === 9
  )
}
// 销审
function checkIfRenderSalesReview(row) {
  return (
    proxy.$store.state.permission.systemConfig.allow_repair_approval !== 0 &&
    row.status === 1 &&
    row.source != 1
  )
}
// 撤回
function checkIfRenderRecall(row) {
  return (
    (row.status === 9 ||
      (proxy.$store.state.permission.systemConfig.allow_repair_approval == 0 &&
        row.status === 1)) &&
    row.source != 1
  )
}
function removeIfRender(row) {
  return (
    row.status === 7 &&
    (row.repairUser === proxy.$store.state.user.userInfo.user.id ||
      proxy.$store.state.user.userInfo.user.type !== 'normal')
  )
}
function cancelFinishIfRender(row) {
  return (
    row.maintainChannel !== 1 &&
    row.status === 4 &&
    row.repairUser === proxy.$store.state.user.userInfo.user.id &&
    (isDispatchUser.value ||
      proxy.$store.state.user.userInfo.user.type !== 'normal')
  )
}
//删除附件
function uploadRemove(file, fileList) {
  registerInfo.formInfo.data.filePathList = fileList
}
function handleExceed() {
  proxy.$message.warning(` 只能上传 ${registerInfo.uploadInfo.limit} 个文件`)
}
function beforeProductUpload(file) {
  //验证文件格式
  let fileTypeArr = file.name.split('.')[file.name.split('.').length - 1]
  if (registerInfo.uploadInfo.fileType.indexOf(fileTypeArr) === -1) {
    proxy.$message.error(
      `文件格式不正确, 请上传 ${registerInfo.uploadInfo.fileType.join(
        ' / '
      )} 格式文件!`
    )
    return false
  }
  let file_type_list = proxy.$store.state.permission.dict['file_type_list']
  if (file_type_list && file_type_list.length) {
    let uploadType = file.name.split('.')[file.name.split('.').length - 1]
    let file_type_list_arr = []
    file_type_list.forEach((item) => {
      file_type_list_arr.push(item.code)
    })
    if (!String(file_type_list_arr).includes(uploadType)) {
      proxy.$message.error({
        message: `文件格式【${uploadType}】非白名单文件类型格式，不支持上传`,
        showClose: true,
        duration: 3500,
      })
      return false
    }
  }
  //验证文件大小
  const maxFileSize = file.size / 1024 / 1024 < registerInfo.uploadInfo.fileSize
  if (!maxFileSize) {
    proxy.$message.error(
      `上传文件大小不能超过${registerInfo.uploadInfo.fileSize}Mb！`
    )
    return false
  }
  //发生请求时打开加载动画
  registerInfo.uploadInfo.loading = ElLoading.service({
    fullscreen: true,
    background: 'rgba(255,255,255,.4)',
  })
  return true
}
//上传附件
function uploadAttachment(resp, file) {
  registerInfo.uploadInfo.loading.close()
  if (resp && resp.success) {
    file.filePath = resp.data[0]
    registerInfo.formInfo.data.filePathList.push(file)
  }
}
function uploadError(err) {
  if (err) {
    ElMessage.error({
      message: '系统错误',
      duration: 3000,
      showClose: true,
    })
  }
  registerInfo.uploadInfo.loading.close()
}
function openRepairUserWindow() {
  const actualMaintenanceUser =
    sendOrderInfo.formInfo.data.actualMaintenanceUser
  if (
    actualMaintenanceUser &&
    actualMaintenanceUser != -2 &&
    sendOrderInfo.title === '改派'
  ) {
    selectRepairUserInfo.query.userIdNotIn = actualMaintenanceUser
  }
  selectRepairUserInfo.query.orgId =
    sendOrderInfo.formInfo.data.maintenanceId === -2
      ? ''
      : sendOrderInfo.formInfo.data.maintenanceId
  selectRepairUserInfo.query.assetId =
    sendOrderInfo.formInfo.data.assetId === -2
      ? ''
      : sendOrderInfo.formInfo.data.assetId
  selectRepairUserInfo.query.deptId =
    sendOrderInfo.formInfo.data.useDeptId === -2
      ? ''
      : sendOrderInfo.formInfo.data.useDeptId
  selectRepairUserInfo.query.depotId =
    sendOrderInfo.formInfo.data.depotId === -2
      ? ''
      : sendOrderInfo.formInfo.data.depotId
  selectRepairUserInfo.query.assetClassifyId =
    sendOrderInfo.formInfo.data.classifyType === -2
      ? ''
      : sendOrderInfo.formInfo.data.classifyType
  selectRepairUserInfo.query.notAssetRepairType =
    sendOrderInfo.formInfo.data.notAssetRepairType === -2
      ? ''
      : sendOrderInfo.formInfo.data.notAssetRepairType
  selectRepairUserInfo.visible = true
}
function pageInfo(obj) {
  page = obj
}
function handleCloseSendOrder() {
  sendOrderInfo.visible = false
}
function handleCloseRegister() {
  registerInfo.visible = false
}
function handleCloseFinish() {
  finishInfo.visible = false
}
function handleCloseEstimate() {
  estimateInfo.visible = false
}
function showProductDetail(row) {
  getBusinessKeyById({
    businessKey: row.orderNo,
    businessType: 'repairApply',
  }).then((res) => {
    if (res.success) {
      sessionStorage.setItem('storeRowId', row.id)
      if (res.data?.processInstanceId) {
        proxy.$fn.setFlowData(res.data, '', proxy.$route)
      } else {
        detailInfo.visible = true
        detailInfo.title = '报修单详情'
        detailInfo.id = row.id
      }
    }
  })
}
function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
function returnModify() {
  if (modifyInfo.id) {
    getList()
  } else {
    search()
  }
}
//派单
function sendOrder(row) {
  sendOrderInfo.formInfo.data = {}
  sendOrderInfo.visible = true
  sendOrderInfo.title = '派单'
  sendOrderInfo.formInfo.data.orderId = row.id
  sendOrderInfo.formInfo.data.orderType = 53
  sendOrderInfo.formInfo.data.userId = row.acceptUser
  sendOrderInfo.formInfo.data.actualMaintenanceUser = row.actualMaintenanceUser
  sendOrderInfo.formInfo.data.assetId = row.assetId
  sendOrderInfo.formInfo.data.repairType = row.repairType
  sendOrderInfo.formInfo.data.maintenanceId =
    row.maintainChannel === 1 ? row.maintenanceId : ''
  sendOrderInfo.formInfo.data.classifyType = row.classifyType
  sendOrderInfo.formInfo.data.useDeptId = row.useDeptId
  sendOrderInfo.formInfo.data.depotId = row.depotId
  sendOrderInfo.formInfo.data.requireCompleteTime = row.expectCompleteTime
  sendOrderInfo.formInfo.data.notAssetRepairType = row.notAssetRepairType
  selectRepairUserInfo.checkedRowList = []
  proxy.$nextTick(() => {
    sendOrderInfo.formInfo.ref.clearValidate()
  })
}
//改派
function updateSendOrder(row) {
  sendOrderInfo.formInfo.data = {}
  sendOrderInfo.visible = true
  sendOrderInfo.title = '改派'
  sendOrderInfo.formInfo.data.orderId = row.id
  sendOrderInfo.formInfo.data.orderType = 53
  sendOrderInfo.formInfo.data.actualMaintenanceUser = row.actualMaintenanceUser
  sendOrderInfo.formInfo.data.userId = row.pendAcceptUser
  sendOrderInfo.formInfo.data['requireCompleteTime'] = row.requireCompleteTime
  sendOrderInfo.formInfo.data['dispatchDescribe'] = row.dispatchDescribe
  sendOrderInfo.formInfo.data.assetId = row.assetId
  sendOrderInfo.formInfo.data.repairType = row.repairType
  sendOrderInfo.formInfo.data.classifyType = row.classifyType
  sendOrderInfo.formInfo.data.useDeptId = row.useDeptId
  sendOrderInfo.formInfo.data.depotId = row.depotId
  selectRepairUserInfo.checkedRowList = []
  proxy.$nextTick(() => {
    sendOrderInfo.formInfo.ref.clearValidate()
  })
}
//选择维修人员
function selectRepairUserCallBack(row) {
  if (row && row.length) {
    selectRepairUserInfo.checkedRowList = row
    const userIds = []
    const userNames = []
    row.forEach((item) => {
      userIds.push(item.userId)
      userNames.push(item.name)
    })
    sendOrderInfo.formInfo.data['acceptUser'] = userIds.join(',')
    sendOrderInfo.formInfo.data['acceptUserName'] = userNames.join(',')
  } else {
    selectRepairUserInfo.checkedRowList = []
    sendOrderInfo.formInfo.data['acceptUser'] = ''
    sendOrderInfo.formInfo.data['acceptUserName'] = ''
  }
}
//派单保存
function saveSendOrder() {
  sendOrderInfo.formInfo.data.dispatchType = 0
  sendOrderInfo.formInfo.ref.validate((valid) => {
    if (valid) {
      if (sendOrderInfo.title === '派单') {
        dispatchRepairOrder(sendOrderInfo.formInfo.data).then((resp) => {
          if (resp && resp.success) {
            getList()
          }
          sendOrderInfo.visible = false
        })
      } else {
        updateDispatchRepairOrder(sendOrderInfo.formInfo.data).then((resp) => {
          if (resp && resp.success) {
            getList()
          }
          sendOrderInfo.visible = false
        })
      }
    }
  })
}
//处理登记
function handleRegister(row) {
  registerInfo.formInfo.data = {}
  registerInfo.visible = true
  registerInfo.formInfo.data.dealUser = proxy.$store.state.user.userInfo.user.id
    ? proxy.$store.state.user.userInfo.user.id
    : ''
  registerInfo.formInfo.data.dealUserName = proxy.$store.state.user.userInfo
    .user.name
    ? proxy.$store.state.user.userInfo.user.name
    : ''
  registerInfo.formInfo.data.orderId = row.id
  registerInfo.formInfo.data.filePathList = []
  registerInfo.uploadInfo.fileList = []
  registerInfo.formInfo.data.orderType = 53
  proxy.$nextTick(() => {
    registerInfo.formInfo.ref.clearValidate()
  })
}
//处理登记保存
function saveRegister() {
  registerInfo.formInfo.ref.validate((valid) => {
    if (valid) {
      repairDealAffair(registerInfo.formInfo.data).then((resp) => {
        if (resp && resp.success) {
          getList()
        }
        registerInfo.visible = false
      })
    }
  })
}
//完工
function finish(row) {
  finishInfo.formInfo.data = {
    completeTime: moment(new Date()).format('YYYY-MM-DD HH:mm'),
  }
  finishInfo.visible = true
  finishInfo.formInfo.data.id = row.id
  proxy.$nextTick(() => {
    finishInfo.formInfo.ref.clearValidate()
  })
}
//完工保存
function saveFinish() {
  finishInfo.formInfo.ref.validate((valid) => {
    if (valid) {
      completeDealRepairOrder(finishInfo.formInfo.data).then((resp) => {
        if (resp && resp.success) {
          getList()
        }
        finishInfo.visible = false
      })
    }
  })
}
//取消完工
function cancelFinish(row) {
  cannelRepairOrder(row.id).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
// 审批/拒绝/驳回按钮审批原因弹窗
function btnFlow(row, code) {
  const currentBtnFlow = {
    title: '',
    api: null,
  }
  if (code === 'approve') {
    currentBtnFlow.api = approvedRepairOrder
    const data = {
      orderId: row.id,
    }
    currentBtnFlow.api(data).then((resp) => {
      if (resp && resp.success) {
        getList()
      }
    })
    return
  } else if (code === 'reject') {
    currentBtnFlow.title = '驳回'
    currentBtnFlow.api = rejectRepairOrder
  } else if (code === 'refuse') {
    currentBtnFlow.title = '拒绝'
    currentBtnFlow.api = refuseRepairOrder
  }
  proxy
    .$prompt('请输入' + currentBtnFlow.title + '理由', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValidator: proxy.$fn.maxString200,
      inputErrorMessage: currentBtnFlow.title + '理由不能超过200字符',
    })
    .then(({ value }) => {
      const data = {
        orderId: row.id,
        checkOpt: value,
      }
      currentBtnFlow.api(data).then((resp) => {
        if (resp && resp.success) {
          getList()
        }
      })
    })
}
// 撤回
function recall(row) {
  recallRepairOrder([row.id]).then((res) => {
    if (res && res.success) {
      getList()
      ElMessage.success({
        message: '操作成功',
        duration: 3000,
        showClose: true,
      })
    } else {
      ElMessage.error({
        message: res.msg,
        duration: 3000,
        showClose: true,
      })
    }
  })
}
// 销审
function salesReview(row) {
  cancelCheckRepairOrder([row.id]).then((res) => {
    if (res && res.success) {
      getList()
      ElMessage.success({
        message: '操作成功',
        duration: 3000,
        showClose: true,
      })
    } else {
      ElMessage.error({
        message: res.msg,
        duration: 3000,
        showClose: true,
      })
    }
  })
}
//评价
function estimate(row) {
  estimateInfo.formInfo.data = {}
  estimateInfo.visible = true
  estimateInfo.formInfo.data.id = row.id
}
//评价保存
function saveEstimate() {
  confirmRepairOrder(estimateInfo.formInfo.data).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
    estimateInfo.visible = false
  })
}
//撤销
function revoke(row) {
  revokeRepairOrder(row.id).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
function reminder(row = undefined) {
  let ids = []
  if (row) {
    ids.push(row.id)
  } else {
    tableInfo.selections.forEach((item) => {
      ids.push(item.id)
    })
  }
  reminderRepairOrder(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
//删除
function remove(row) {
  const data = []
  data.push(row.id)
  deleteRepairOrder(data).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
// 创建
function create() {
  modifyInfo.visible = true
  modifyInfo.title = '新增报修单'
  modifyInfo.id = null
}
// 修改
function update(row) {
  getBusinessKeyById({
    businessKey: row.orderNo,
    businessType: 'repairApply',
  }).then((res) => {
    if (res.success) {
      if (res.data?.processInstanceId) {
        proxy.$fn.setFlowData(res.data, '', proxy.$route)
      } else {
        modifyInfo.visible = true
        modifyInfo.title = '修改报修单'
        modifyInfo.id = row.id
      }
    }
  })
}
// 提交
function submit(row) {
  const params = {
    // flowTaskCommentDto和processDefinitionKey为审批流程需要传递的参数
    flowTaskCommentDto: { approvalType: 'submit' },
    processDefinitionKey: 'repairApply',
    orderId: row.id,
  }
  submitRepairOrder(params).then((res) => {
    if (res && res.success) {
      getList()
      ElMessage.success({
        message: '操作成功',
        duration: 3000,
        showClose: true,
      })
    } else {
      ElMessage.error({
        message: res.msg,
        duration: 3000,
        showClose: true,
      })
    }
  })
}
function _delete(row) {
  deleteSavedRepairOrder(row.id).then((res) => {
    if (res && res.success) {
      getList()
      ElMessage.success({
        message: '操作成功',
        duration: 3000,
        showClose: true,
      })
    } else {
      ElMessage.error({
        message: res.msg,
        duration: 3000,
        showClose: true,
      })
    }
  })
}
function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.visible = true
}
async function advancedSearchCallback(obj) {
  filterInfo.query.queryMap = {}
  let arr = [
    {
      asTbName: 'repair_order',
      columnName: 'repair_dept_id',
      queryType: 'IN',
      queryCategory: 'AND',
      value: 'deptAuth',
    },
  ]
  filterInfo.query.queryDtoList = [...obj.queryDtoList, ...arr]
  advancedSearchInfo.data = obj.data
  await getList()
  clearType.value = !clearType.value
  filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap)
}
async function getList() {
  tableInfo.refresh = Math.random()
}
function search() {
  advancedSearchInfo.data = {}
  filterInfo.query.queryDtoList = []
  tableInfo.initCurpage = Math.random()
  tableInfo.refresh = Math.random()
}
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = [...data]
      break
  }
}
function clearSearch() {
  clearType.value = !clearType.value
  filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap)
  filterInfo.query.queryParams.isSatisfaction = ''
  search()
}
function getCustomize(val = true) {
  let param = {
    tableKey:
      'repairRepairOrderList-com.slip.spd.entity.vo.repair.RepairOrderVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.query.customizeUserVO = data
      tableInfo.fieldList = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.searchList,
        data.detail
      )
      filterInfo.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.query.queryMap,
      }
      filterInfo.searchList = [
        ...searchInfo.searchList,
        {
          label: '是否满意',
          value: 'isSatisfaction',
          slot: 'true',
        },
      ]
      filterInfo.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.copyQueryMap = proxy.$fn.deepClone(filterInfo.query.queryMap)
      slipSelectRequest.value = val
      tableInfo.api = getRepairOrderCustomizeListPage
      getList()
    }
  })
}
function returnUpdate(id) {
  detailInfo.visible = false
  modifyInfo.visible = true
  modifyInfo.title = '修改报修单'
  modifyInfo.id = id
}
</script>

<style scoped>
.i-more-disabled {
  cursor: not-allowed;
}
.i-more {
  background-color: #ffffff;
  cursor: pointer;
  height: 26px;
}
</style>
